<template>
  <a-modal :title="$t('Client') + ' ip ' + $t('Operate')" v-model="edcliet" @cancel="cancelhandle" width="48%" @ok="subnew"
    :cancelText="$t('Cancel')" :okText="$t('Sure')" :maskClosable="false" v-dragModal>
    <a-table :columns="ipcolumns" :dataSource="subdata" bordered :pagination='pagination' size='small'
      :locale="defaultSetting">
      <!-- <template slot="access_type" slot-scope="access_type, record">
          <span v-if="access_type == '1'">{{ $t('读写') }}</span>
          <span v-else-if="access_type == '2'">{{ $t('只读') }}</span>
        </template>
        <template slot="squash" slot-scope="squash, record">
          <span v-if="squash == '1'">no_root_squash</span>
          <span v-else-if="squash == '2'">root_squash</span>
      </template> -->
      <!-- 编辑ip -->
      <template v-for="col in ['access_type']" :slot="col" slot-scope="text, record, index">
        <div :key="col">
          <a-select :defaultValue="text" style="width: 120px" v-if="record.editable"
            @change="e => handleChange(e, record, col)">
            <a-select-option value='只读'>{{ $t('Read_only') }}</a-select-option>
            <a-select-option value='读写'>{{ $t('Read_and_write') }}</a-select-option>
          </a-select>
          <template v-else>{{ text }}</template>
        </div>
      </template>
      <template v-for="col2 in ['squash']" :slot="col2" slot-scope="text, record, index">
        <div :key="col2">
          <a-select :defaultValue="text" style="width: 120px" v-if="record.editable"
            @change="e => handleChange2(e, record, col2)">
            <a-select-option value='no_root_squash'>no_root_squash</a-select-option>
            <a-select-option value='root_squash'>root_squash</a-select-option>
          </a-select>
          <template v-else>{{ text }}</template>
        </div>
      </template>

      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record)">{{ $t('Save') }} | </a>
            <a-popconfirm :title="$t('Sure-cancel-tip')" :ok-text="$t('Sure')" :cancel-text="$t('Cancel')"
              @confirm="() => cancel(record.key)">
              <a>{{ $t('Cancel') }}</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="() => edit(record.ip)">{{ $t('Edit') }} | </a>

            <!-- 删除ip -->
            <a-popconfirm v-if="subdata.length" :title="$t('Sure-del-tip')" :ok-text="$t('Sure')"
              :cancel-text="$t('Cancel')" @confirm="() => onDelete(record)">
              <a href="javascript:;">{{ $t('Delete') }}</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>

    <!--添加客户端ip-->
    <a-button class="editable-add-btn" @click="handleAdd">{{ $t('Add') }}{{ $t('Client') }}ip</a-button>
    <div id="components-form-demo-advanced-search" v-if="flag">
      <a-spin size="large"
        style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%"
        tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
      <a-form :form="form" class="ant-advanced-search-form">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label='IP' has-feedback>
              <a-input v-decorator="['ip', {
                rules: [{ required: true, message: $t('Enter') + ' ip' },
                { pattern: /^(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])|(\*))\.(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\*))\.(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\*))\.((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$)|(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([1-2][0-9]|3[0-2]|[1-9]))$)|((\*)$))/, message: $t('IP_format') }]
              }]" :placeholder="$t('Enter') + ' ip'" />
              <!-- 没有通配符*的情况：/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$|(\/([1-2][0-9]|3[0-2]|[1-9])$)/ -->
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :label="$t('Access-permission')" has-feedback>
              <a-select v-decorator="['access_type', {
                rules: [{ required: true, message: $t('Choose') + $t('Access-permission') }]
              }]" :placeholder="$t('Choose') + $t('Access-permission')">
                <a-select-option value='1'>{{ $t('Read_and_write') }}</a-select-option>
                <a-select-option value='2'>{{ $t('Read_only') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8" id='subuser_permissions'>
            <a-form-item :label="$t('Compress')" has-feedback>
              <a-select v-decorator="['squash', {
                rules: [{ required: true, message: $t('Choose') + 'squash' }]
              }]" :placeholder="$t('Choose') + 'squash'">
                <a-select-option value='1'>no_root_squash</a-select-option>
                <a-select-option value='2'>root_squash</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="sureadd">{{ $t('Add') }}</a-button>
            <a-button type="default" :style="{ marginLeft: '8px' }" @click="handleReset">{{ $t('Clear') }}</a-button>
            <!-- <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="flag=false">{{$t('Finished')}}</a> -->
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import request from '@/request/request'

export default {
  props: ["ss", "tarname"],
  components: { EmptyData },
  data() {
    return {
      form: this.$form.createForm(this),
      formlayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 14 }
      },
      pagination: {
        defaultPageSize: 5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '15', '20', '25'],
        onShowSizeChange: (current, pageSize) => this.pageSize = pageSize,
        buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      ipcolumns: [
        { title: this.$t('Client'), dataIndex: 'ip', key: 'ip', scopedSlots: { customRender: "ip" } },
        { title: this.$t('Access-permission'), dataIndex: 'access_type', key: 'access_type', scopedSlots: { customRender: "access_type" } },
        { title: this.$t('Compress'), dataIndex: 'squash', key: 'squash', scopedSlots: { customRender: "squash" } },
        { title: this.$t('Operate'), dataIndex: "operation", key: "operation", scopedSlots: { customRender: "operation" } }
      ],
      edcliet: false,
      accessMap: new Map([
        ['读写', 1],
        ['只读', 2],
      ]),
      squashMap: new Map([
        ['no_root_squash', 1],
        ['root_squash', 2],
      ]),
      flag: false,
      spinning: false,
      subdata: [],
      hasCancel: false,
      defaultSetting: { emptyText: <EmptyData /> }
    };
  },
  watch: {
    async ss(val) {
      this.edcliet = val;
      await this.getList()
      localStorage.setItem('clients', JSON.stringify(this.subdata))
    },
    getlanguage(val) {  //监听语言切换，切换data组件内的多语言
      this.ipcolumns = [
        { title: this.$t('Client'), dataIndex: 'ip', key: 'ip', scopedSlots: { customRender: "ip" } },
        { title: this.$t('Access-permission'), dataIndex: 'access_type', key: 'access_type', scopedSlots: { customRender: "access_type" } },
        { title: this.$t('Compress'), dataIndex: 'squash', key: 'squash', scopedSlots: { customRender: "squash" } },
        { title: "operation", dataIndex: "operation", key: "operation", scopedSlots: { customRender: "operation" } }
      ]
    }
  },
  computed: {
    getlanguage() {
      return this.$store.state.language
    }
  },
  methods: {
    async getList() {
      const { data } = await request('get', 'cephfs/ganesha/client', { export_id: this.tarname.id })
      data.map(item => {
        if (item.access_type == 1) item.access_type = '读写'
        else if (item.access_type == 2) item.access_type = '只读'
        if (item.squash == 1) item.squash = 'no_root_squash'
        else if (item.squash == 2) item.squash = 'root_squash'
      })
      this.subdata = data
    },
    subnew() {
      this.$emit('omodal', false, false);
      this.flag = false;
    },
    cancelhandle() {
      if (this.hasCancel) {
        this.$emit('omodal', false, false);
        this.hasCancel = false;
      } else {
        this.$emit('omodal', false, true);
      }
      this.flag = false;
    },
    //删除客户端ip
    onDelete(key) {
      request('DELETE', "cephfs/ganesha/client/", {
        // data:{
        // fs_name:this.tarname.fs_name,
        path: this.tarname.path,
        export_id: this.tarname.id,
        id: key.id,
        ip: key.ip,
        // }
      })
        .then(async res => {
          this.model(res.data.id); //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag); //通知列表显示
          // this.gettask()  //任务栏信息
          if (res.data.flag == 0) {
            this.hasCancel = true; //防止删除了，然后按了取消，在重新点开，数据没有刷新
            // const newData = [...this.subdata];
            // this.subdata = newData.filter(item => item !== key);
            await this.getList()
          }
        });
    },
    handleChange(value, key, column) {
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item)[0];
      if (target) {
        target[column] = value;
        this.subdata = newData;
      }
    },
    handleChange2(value, key, column) {
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item)[0];
      if (target) {
        target[column] = value;
        this.subdata = newData;
      }
    },
    edit(key) {
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item.ip)[0];
      if (target) {
        target.editable = true;
        this.subdata = newData;
      }
    },
    save(key) {
      const target = key;
      if (target) {
        delete target.editable;
        const params = {
          path: this.tarname.path,
          export_id: this.tarname.id,
          id: target.id,
          ip: target.ip,
          access_type: this.accessMap.get(target.access_type),
          squash: this.squashMap.get(target.squash)
        }
        console.log('params', params)
        // this.$axios.put(this.allurl + "cephfs/nfs/client", {
        request('post', "cephfs/ganesha/client/update", params).then(async res => {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
          // this.gettask()  //任务栏信息
          if (res.data.flag == 0) {
            // this.subdata = newData;
            await this.getList()
          } else {
            this.subdata = JSON.parse(localStorage.getItem('clients'));
          }
        }).catch(err => {

        })
      }
    },
    cancel(key) {
      // const data = this.subdata
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item.key)[0];

      if (target) {
        Object.assign(
          target,
          // this.cacheData.filter(item => key === item.key)[0]
        );
        delete target.editable;
        this.subdata = JSON.parse(localStorage.getItem('clients'));  //确保取消后恢复原数据
      }
    },
    handleAdd() {
      this.flag = true;
    },
    handleReset() {
      this.form.resetFields();
    },
    //添加客户端ip
    sureadd(e) {
      e.preventDefault();
      this.form.validateFields((err, value) => {
        if (!err) {
          this.spinning = true
          request('put', 'cephfs/ganesha/client', {
            // fs_name:this.tarname.fs_name,
            path: this.tarname.path,
            export_id: this.tarname.id,
            ip: value.ip,
            access_type: value.access_type,
            squash: value.squash
          }).then(async res => {
            if (res.data.flag == 0) {
              let flag = true  //设置标志，不能插入重复的对象
              for (const item of this.subdata) {
                if (item.ip === value.ip) {
                  flag = false
                }
              }
              if (flag) {
                this.subdata.push({
                  ip: value.ip,
                  access_type: value.access_type,
                  squash: value.squash
                })
                localStorage.setItem('clients', JSON.stringify(this.subdata))
              }
            }
            this.model(res.data.id) //返回模板
            this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
            await this.getList()
            // this.gettask()  //任务栏信息
            this.spinning = false
            this.form.resetFields();
            this.createip = false
          }).catch(err => {
            this.spinning = false;
            this.createip = false;
            this.form.resetFields();
          })
        }
      })
    },

  }
};
</script>

